package com.common.bean.execption;

import com.common.util.R;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * 自定义登录失败异常信息
 */
@JsonSerialize(using = BaseOauthExceptionSerializer.class)
public class BaseOauthException extends OAuth2Exception {

    public BaseOauthException(String msg, Throwable t) {
        super(msg, t);
    }

    public BaseOauthException(String msg) {
        super(msg);
    }

    public void getJsonGenerator(String path, JsonGenerator gen, BaseOauthException value) throws IOException {
        gen.writeStartObject();

        gen.writeBooleanField("ok", false);
        gen.writeStringField("code", R.FAIL+"");
        gen.writeStringField("error", String.valueOf(value.getHttpErrorCode()));
        gen.writeStringField("msg", value.getMessage());
//        gen.writeStringField("message", "用户名或密码错误");
        gen.writeStringField("path", path);
        gen.writeStringField("timestamp", String.valueOf(new Date().getTime()));
        if (value.getAdditionalInformation()!=null) {
            for (Map.Entry<String, String> entry : value.getAdditionalInformation().entrySet()) {
                String key = entry.getKey();
                String add = entry.getValue();
                gen.writeStringField(key, add);
            }
        }
        gen.writeEndObject();
    }

}